//
//  ALAssetsLibrary category to handle a custom photo album
//
//  Created by Marin Todorov on 10/26/11.
//  Copyright (c) 2011 Marin Todorov. All rights reserved.
//

#import <ImageIO/ImageIO.h>
#import "PHPhotoLibrary+CustomPhotoAlbum.h"
#import "QWImageMangerConfig.h"

@implementation PHPhotoLibrary(CustomPhotoAlbum)

- (void)saveImage:(UIImage*)image toAlbum:(NSString*)albumName withMetaData:(NSDictionary *)metaData withCompletionBlock:(SavePHotoImageCompletionExternal)completionBlock
{
    [self saveImage:image
        orientation:image.imageOrientation
            toAlbum:APP_ALBUM_NAME
       withMetaData:metaData
         completion:completionBlock];
}


- (BOOL)writeData:(NSData *)imageData toFileurl:(NSURL*)fileURL metadata:(NSDictionary *)metadata
{
    CGImageSourceRef source = CGImageSourceCreateWithData((__bridge CFDataRef)imageData, NULL);
    NSMutableDictionary * sourceDic = [NSMutableDictionary dictionary];
    [sourceDic addEntriesFromDictionary:metadata];
    CFStringRef UTI = CGImageSourceGetType(source);
    CGImageDestinationRef destination = CGImageDestinationCreateWithURL((__bridge CFURLRef)fileURL, UTI, 1, NULL);
    CGImageDestinationAddImage(destination, [UIImage imageWithData:imageData].CGImage, (__bridge CFDictionaryRef)sourceDic);
    CGImageDestinationFinalize(destination);
    CFRelease(source);
    CFRelease(destination);
    return YES;
}

- (void)saveImage:(UIImage*)tempimage
      orientation:(UIImageOrientation)srcOrientation
          toAlbum:(NSString*)albumName
     withMetaData:(NSDictionary *)metaData
       completion:(SavePHotoImageCompletionExternal)completionBlock
{
    int orientation;
    switch (srcOrientation) {
        case UIImageOrientationUp:
            orientation = 1;
            break;
        case UIImageOrientationDown:
            orientation = 3;
            break;
        case UIImageOrientationLeft:
            orientation = 8;
            break;
        case UIImageOrientationRight:
            orientation = 6;
            break;
        case UIImageOrientationUpMirrored:
            orientation = 2;
            break;
        case UIImageOrientationDownMirrored:
            orientation = 4;
            break;
        case UIImageOrientationLeftMirrored:
            orientation = 5;
            break;
        case UIImageOrientationRightMirrored:
            orientation = 7;
            break;
        default:
            orientation = 1;
            break;
    }
    //orientation = 6;
    NSMutableDictionary *mutableMetaData = [NSMutableDictionary dictionaryWithDictionary:metaData];
    [mutableMetaData setObject:[NSNumber numberWithInt:orientation] forKey:(NSString *)kCGImagePropertyOrientation];
    metaData = [NSDictionary dictionaryWithDictionary:mutableMetaData];
    
    NSDateFormatter *format = [[NSDateFormatter alloc] init];
    [format setDateFormat:@"yyyy-dd-MM-HH-mm-ss"];
    NSString *strDate = [format stringFromDate:[NSDate date]];
    
    NSString *saveDir = [QWImageMangerConfig createAFolderOnDisk:UPLOAD_DIR];
    NSString *fileName = [NSString stringWithFormat:@"%@_%dTemp.png",strDate, 1];
    NSString *uploadPhotoPath = [saveDir stringByAppendingPathComponent:fileName];
    NSURL *url = [NSURL fileURLWithPath:uploadPhotoPath];
    
    __block  NSString  *strIdentifier = nil;
    dispatch_async(dispatch_get_main_queue(), ^{
        //write the image data to the assets library (camera roll)
        [self writeData:UIImageJPEGRepresentation(tempimage, 1) toFileurl:url metadata:metaData];
        [self performChanges:^{
            BOOL hasFile = [[NSFileManager defaultManager] fileExistsAtPath:uploadPhotoPath];
            if (hasFile)
            {
                PHAssetChangeRequest *request = [PHAssetChangeRequest creationRequestForAssetFromImageAtFileURL:url];
                PHObjectPlaceholder *placeholderAsset = request.placeholderForCreatedAsset;
                strIdentifier = placeholderAsset.localIdentifier;
                //DebugLog(@"placeholderAsset:%@ request:%@",placeholderAsset,request);
                if ([albumName length] && request != nil && placeholderAsset != nil)
                {
                    [self addAssetURL:placeholderAsset toAlbum:albumName withCompletionBlock:nil];
                }else
                {
#if DEBUG
                    NSLog(@"saveImage to album fail bacuse request = %@ placeholderAsset =%@",request,placeholderAsset);
#endif
                }
            }else
            {
#if DEBUG
                NSLog(@"uploadPhotoPath has nos no file");
#endif
            }
            
        } completionHandler:^(BOOL success,NSError *error){
            
            dispatch_async(dispatch_get_main_queue(), ^{
                if (success)
                {
                    completionBlock(strIdentifier, error);
                }else
                {
#if DEBUG
                    completionBlock(nil, error);
                    NSLog(@"save image date:%@ error:%@",[NSDate date],error);
#endif
                    
                }
            });
            
            NSError  *fileerror = nil;
            BOOL successRemove = [[NSFileManager defaultManager] removeItemAtPath:uploadPhotoPath
                                                                            error:&fileerror];
            if (!successRemove)
            {
                //DebugLog(@"removeItemAtPath:%@ fail  because error:%@",uploadPhotoPath,fileerror);
            }
        }];
    });
}


-(void)addAssetURL:(PHObjectPlaceholder*)assetPlaceholder toAlbum:(NSString*)albumName withCompletionBlock:(SavePHotoImageCompletionExternal)completionBlock
{
    
    PHFetchResult *smartAlbums = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeSmartAlbum subtype:PHAssetCollectionSubtypeAny options:nil];
    PHFetchResult *userAlbums = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeAny options:nil];
    
    NSMutableArray *tempArray = [NSMutableArray array];
    if (smartAlbums) {
        [tempArray addObject:smartAlbums];
    }
    
    if (userAlbums) {
        [tempArray addObject:userAlbums];
    }
    __block BOOL hasCollect = NO;
    __block PHAssetCollection *assetCollection = nil;
    
    for (int i = 0; i < tempArray.count; i++)
    {
        PHFetchResult *collections = [tempArray objectAtIndex:i];
        
        [collections enumerateObjectsUsingBlock:^(PHAssetCollection *obj, NSUInteger idx, BOOL *stop){
            
            if ([albumName isEqualToString:obj.localizedTitle])
            {
                assetCollection = obj;
                PHAssetCollectionChangeRequest *request = [PHAssetCollectionChangeRequest changeRequestForAssetCollection:assetCollection];
                [request addAssets:@[assetPlaceholder]];
                hasCollect = YES;
                *stop = YES;
            }
            // NSLog(@"obj.names:%@",obj.localizedTitle);
            
            
        }
         ];
    }
    
    if (!hasCollect || assetCollection == nil){
        PHAssetCollectionChangeRequest *request = [PHAssetCollectionChangeRequest creationRequestForAssetCollectionWithTitle:albumName];
        [request addAssets:@[assetPlaceholder]];
    }
    
    //search all photo albums in the library
    
}

@end
